﻿using huaxin_core;
using huaxin_Impl;
using huaxin_Interface;
using huaxin_luckdraw.WxPayHelp;
using huaxin_Model;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.TenPayLibV3;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Web.Controllers;


namespace huaxin_luckdraw.Controllers
{
    public class PayController:Controller
    {
        private readonly huaxin_IPayOrder _pay = new huaxin_PayOrderImpl();

        [HttpPost]
        public JsonResult WxpayParam(string OrderId)
        {
            #region
            //Debuglog("开始微信支付:" + OrderId, "wxhd.txt");
            var jsonRes = new object();
            //if (string.IsNullOrEmpty(OrderId))
            //{
            //    jsonRes = new
            //    {
            //        state = false,
            //        error_code = "10000",
            //        error_msg = "信息错误"
            //    };
            //}
            //PayOrder order = _pay.GetByOrderId(OrderId);
            ////string curTimeStamp = GetTimeStamp();
            //string timeStamp = "";
            //string nonceStr = "";
            //string paySign = "";

            ////创建支付应答对象
            //RequestHandler packageReqHandler = new RequestHandler(null);
            ////初始化
            //packageReqHandler.Init();

            //#region 预提交提交

            //timeStamp =TenPayV3Util.GetTimestamp();
            //nonceStr = TenPayV3Util.GetNoncestr();

            ////设置package订单参数
            //packageReqHandler.SetParameter("appid", Appid);//公众账号ID
            //packageReqHandler.SetParameter("mch_id", MchId);//商户号
            //packageReqHandler.SetParameter("nonce_str", nonceStr);//随机字符串
            //packageReqHandler.SetParameter("body", order.ProductName);//商品信息
            //packageReqHandler.SetParameter("out_trade_no", order.OrderId + "-" + curTimeStamp);//商家订单号
            //packageReqHandler.SetParameter("total_fee", (order.PayAmount * 100).ToString("F0"));//商品金额,以分为单位(money * 100).ToString()
            //packageReqHandler.SetParameter("spbill_create_ip", (Request.UserHostAddress == "127.0.0.1" || Request.UserHostAddress == "::1") ? "" : Request.UserHostAddress);//用户的公网ip，不是商户服务器IP
            //packageReqHandler.SetParameter("notify_url", Notify);//接收财付通通知的URL
            ////packageReqHandler.SetParameter("trade_type", Senparc.Weixin.MP.TenPayV3Type.JSAPI.ToString());//交易类型
            //packageReqHandler.SetParameter("trade_type", TenPayV3Type.JSAPI.ToString());
            //packageReqHandler.SetParameter("openid", order.OpenId);//用户的openId

            //string sign = packageReqHandler.CreateMd5Sign("key", Key);
            //packageReqHandler.SetParameter("sign", sign);//签名

            //string data = packageReqHandler.ParseXML();
            //Debuglog("data:" + data, "wxhd.txt");

            //var result = TenPayV3.Unifiedorder(data);

            //var res = System.Xml.Linq.XDocument.Parse(result);

            //Debuglog("微信支付参数:" + result, "wxhd.txt");
            //if (res.Element("xml").Element("return_code").Value.ToUpper() == "SUCCESS")
            //{
            //    if (res.Element("xml").Element("return_code").Value.ToUpper() == "SUCCESS" && res.Element("xml").Element("result_code").Value.ToUpper() == "SUCCESS")
            //    {

            //        string prepayId = res.Element("xml").Element("prepay_id").Value;

            //        //设置支付参数
            //        Senparc.Weixin.MP.TenPayLibV3.RequestHandler paySignReqHandler = new Senparc.Weixin.MP.TenPayLibV3.RequestHandler(null);
            //        paySignReqHandler.SetParameter("appId", Appid);
            //        paySignReqHandler.SetParameter("timeStamp", timeStamp);
            //        paySignReqHandler.SetParameter("nonceStr", nonceStr);
            //        paySignReqHandler.SetParameter("package", string.Format("prepay_id={0}", prepayId));
            //        paySignReqHandler.SetParameter("signType", "MD5");
            //        paySign = paySignReqHandler.CreateMd5Sign("key", Key);

            //        jsonRes = new
            //        {
            //            State = true,
            //            param = new
            //            {
            //                appId = Appid,
            //                timeStamp = timeStamp,
            //                nonceStr = nonceStr,
            //                package = string.Format("prepay_id={0}", prepayId),
            //                signType = "MD5",
            //                paySign = paySign
            //            }
            //        };
            //    }
            //    //订单已付款
            //    else if (res.Element("xml").Element("return_code").Value.ToUpper() == "SUCCESS" && res.Element("xml").Element("err_code").Value.ToUpper() == "ORDERPAID")
            //    {
            //        jsonRes = new
            //        {
            //            State = false,
            //            error_code = "42049",
            //            error_info = "支付成功"
            //        };
            //    }
            //    else
            //    {
            //        jsonRes = new
            //        {
            //            State = false,
            //            error_code = "42048",
            //            error_info = "return_code:" + res.Element("xml").Element("return_code").Value + " return_msg:" + res.Element("xml").Element("return_msg").Value + " err_code_des:" + res.Element("xml").Element("err_code_des").Value
            //        };
            //    }
            //}
            //else
            //{
            //    jsonRes = new
            //    {
            //        State = false,
            //        error_code = "42048",
            //        error_info = "return_code:" + res.Element("xml").Element("return_code").Value + " return_msg:" + res.Element("xml").Element("return_msg").Value
            //    };
            //}

            //#endregion

            ////Debuglog("微信下单返回参数" + res, "wxhd.txt");
            #endregion
            return Json(jsonRes, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="productName"></param>
        /// <param name="phone"></param>
        /// <param name="prizeQQ"></param>
        /// <param name="platform">1IOS微信   2android   3IOS QQ  android QQ</param>
        /// <returns></returns>
        public JsonResult WxUnifiedOrder(string productId, string productName,
            string phone,string prizeQQ,int platform)
        {
            var jsonRes = new object();
            if (string.IsNullOrEmpty(productId) && string.IsNullOrEmpty(productName))
            {
                jsonRes = new
                {
                    state = false,
                    error_code = "400",
                    error_msg = "客户端请求参数错误"
                };
            }
            else
            {
                string curTimeStamp = WxAuxiliary.GetTimeStamp();
                huaxin_order payOrder = new huaxin_order();
                payOrder.OrderId = string.Format("{0}{1}", WxAuxiliary.GetOrderNumber("wx-"),
                    curTimeStamp);
                payOrder.ProductId = WxAuxiliary.GetOrderNumber("");
                payOrder.Ip = (Request.UserHostAddress == "127.0.0.1" || Request.UserHostAddress == "::1") ? "" : Request.UserHostAddress;
                payOrder.OpenId = "";
                payOrder.TimeStart = DateTime.Now;
                payOrder.PublishDate = payOrder.TimeStart;
                payOrder.TimeExpire = payOrder.TimeStart.Value.AddMinutes(30);
                payOrder.Remark = productName;
                payOrder.PaymentAmount = 0.1M;
                payOrder.PayStyle = 1;
                payOrder.Platform = platform;
                payOrder.Phone = phone;
                payOrder.PrizeQQ = prizeQQ;

                //huaxin_IPayOrder _payOrder = new huaxin_PayOrderImpl();
                //int result = _payOrder.AddOrder(payOrder);

                #region  下单业务处理
                if (payOrder.PaymentAmount > 0.0M)
                {
                    var unifiedOrder = UnifiedOrder.CreatePayModel(payOrder, productName);
                    var orederResult = UnifiedOrder.GetSendOrderResult(unifiedOrder);
                    if (orederResult.IsResultCodeSuccess())
                    {
                        huaxin_IPayOrder _payOrder = new huaxin_PayOrderImpl();
                        int result = _payOrder.AddOrder(payOrder);
                        if (result > 0)
                        {
                            jsonRes = new
                            {
                                state = true,
                                error_code = "200",
                                error_msg = orederResult.code_url,
                                code_url= orederResult.code_url,
                                order_no= payOrder.OrderId
                            };
                        }
                        else
                        {
                            jsonRes = new
                            {
                                state = false,
                                error_code = "400",
                                error_msg = "下单失败",
                                code_url = "",
                                order_no = ""
                            };
                        }
                    }
                }
                #endregion
            }

            return Json(jsonRes, JsonRequestBehavior.AllowGet);
        }

    }
}